/**
 * 关闭websorket连接
 * @param {number} id - 接收端id
 * @param {string}  [wtoken] 关闭指定用户连接 配合id 可选
 */
function WSclose(id, wtoken) {
	try {
		if (wsClients[id] !== undefined) {
			if (wtoken != undefined) {
				wsClients[id] = wsClients[id].filter((client) => {
					if (client.wtoken === wtoken) {
						client.close()
					}
					return client.wtoken != wtoken;
				})
			} else {
				wsClients[id].forEach((client) => {
					client.close()
				});
			}
			if (wsClients[id].length == 0) {
				delete wsClients[id]
				delete wsClientUsers[id]
			}
		}
	} catch (e) {
		//TODO handle the exception
	}
}
/**
 * 指定id发送数据
 * @param {object} data - 发送的数据
 * @param {number} id - 接收端id
 * @param {string}  [wtoken] 指定接收端 配合id 可选
 */
function WSsendMessage(data, id, wtoken) {
	try {
		if (wsClients[id] !== undefined) {
			if (wtoken != undefined) {
				wsClients[id].forEach((client) => {
					if (client.wtoken === wtoken) {
						//只发单端用户
						client.send(JSON.stringify(data));
					}
				});
			} else {
				//发给 所有端 同一用户
				wsClients[id].forEach((client) => {
					client.send(JSON.stringify(data));
				});
			}
		}
	} catch (e) {}
}
/**
 * 群发数据
 * @param {object} data - 发送的数据
 * @param {number} [id] - 不接收端 id
 * @param {string}  [wtoken] 指定不接收端 配合id 可选
 */
function WSsendAll(data, id, wtoken) {
	try {
		if (id == undefined && wtoken == undefined) {
			for (let key in wsClients) {
				wsClients[key].forEach((client) => {
					client.send(JSON.stringify(data));
				});
			}
		} else if (id && wtoken) {
			for (let key in wsClients) {
				if (key != id && wsClients[key].wtoken != wtoken) {
					wsClients[key].forEach((client) => {
						client.send(JSON.stringify(data));
					});
				}
			}
		} else if (id) {
			for (let key in wsClients) {
				if (key != id) {
					wsClients[key].forEach((client) => {
						client.send(JSON.stringify(data));
					});
				}
			}
		}
	} catch (e) {}
}


/**
 * 集中生成新token 推送新的用户信息 更新用户信息用
 */


module.exports = {
	WSclose,
	WSsendMessage,
	WSsendAll
};